/* eslint-disable @typescript-eslint/no-var-requires */
import { RouteRecordRaw } from 'vue-router'

let firstMenu: any = null //定义变量接受第一个匹配的路由路径

export function mapMenusToRouters(userMenus: any): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []
  // 1.先加载所有的routes
  const allRoutes: RouteRecordRaw[] = []
  const routeFiles = require.context('../router/main', true, /\.ts/)
  // console.log(routeFiles)
  routeFiles.keys().forEach((key) => {
    const route = require('../router/main' + key.split('.')[1]) //分割截取索引1之前的字符串
    allRoutes.push(route.default)
  })

  // console.log(allRoutes)
  // 2.根据菜单获取需要添加的routes
  // 递归设置动态添加路由
  const recurseGetRoute = (menus: any[]) => {
    for (const menu of menus) {
      if (menu.type === 2) {
        const routeNew = allRoutes.find((item) => {
          // console.log(item.path, menu.url)
          return item.path == menu.url
        })

        // 判断赋值第一次 第二次就有赋过值了就不会进入
        if (!firstMenu) {
          firstMenu = menu
          // console.log(firstMenu)
        }
        if (routeNew) routes.push(routeNew)
      } else {
        recurseGetRoute(menu.children)
      }
    }
  }
  recurseGetRoute(userMenus)
  return routes
}

// 匹配路由和菜单 递归
export function pathMapToMenu(userMenus: any[], currentPath: string): any {
  for (const menu of userMenus) {
    if (menu.type === 1) {
      const findMenu = pathMapToMenu(menu.children ?? [], currentPath)
      if (findMenu) {
        return findMenu
      }
    } else if (menu.type === 2 && menu.url === currentPath) {
      return menu
    }
  }
}

export { firstMenu }
